#!/usr/bin/bash

function usage() {
	echo "Usage: $( basename $0 ) archive strings_to_search" 1>&2
	exit 1
}

CHECK_FILE_TYPE_CMD="file --mime-type -L -b"

function extractTar() {
        FILENAME="$1"
        DIRECTORY="$2"
	tar xf "$FILENAME" -C "$DIRECTORY"
}

function handleTar() {
	FILENAME="$1"
	DIRECTORY="$2"
	if test "x$( $CHECK_FILE_TYPE_CMD -z "$FILENAME")" == "xapplication/x-tar"; then
		echo "Found nested archive, using tar" 1>&2
		extractTar "$FILENAME" "$DIRECTORY"
		return 0
	fi
	return 1
}

function unArchiveCMD() {
	FILENAME="$1"
	DIRECTORY="$2"
	MIMETYPE="$( $CHECK_FILE_TYPE_CMD "$1")"
        case "$MIMETYPE" in
		"application/zip")
		unzip -q "$FILENAME" -d "$DIRECTORY"
		;;
		"application/x-tar")
		extractTar "$FILENAME" "$DIRECTORY"
		;;
		"application/x-gzip")
		handleTar "$FILENAME" "$DIRECTORY" || zcat "$FILENAME" > "$DIRECTORY/$( basename "$FILENAME")"
		;;
		"application/x-bzip2")
                handleTar "$FILENAME" "$DIRECTORY" || bzcat "$FILENAME" > "$DIRECTORY/$( basename "$FILENAME")"
		;;
		*)
		echo "Mimetype $MIMETYPE not supported, exiting;" 1>&2
		exit 1
	esac
}

JAR="$1"
shift

test "x$JAR" != "x" || usage

TMPDIR="/tmp/$( basename "$JAR" .jar )"
rm -rf "$TMPDIR"
mkdir -p $TMPDIR

unArchiveCMD "$JAR" "$TMPDIR"


echo "Searching in jar $JAR (tmpdir: $TMPDIR)" 1>&2
grep -irH --colour=yes $@ "$TMPDIR"
rm -rf "$TMPDIR"
